package search.impl;

import search.text.SymbolTable;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TextIndex implements search.text.TextIndex{
    private SymbolTable<String,List<Integer>> table;
    private int n;

    public TextIndex(SymbolTable<String,List<Integer>> table, int n){
        this.table = table;
        this.n = n;
    }

    public void buildIndex(String textName) throws Exception {
        List<String> words = getWords(textName);
        int position = 0;
        for (String word : words) {
            if(table.containsKey(word)){
                table.get(word).add(position);
            } else {
                List<Integer> positions = new ArrayList<Integer>();
                positions.add(position);
                table.put(word,positions);
            }
            position++;
        }
    }

    private List<String> getWords(String textName) {
        int cont = 0;
        List<String> words = new ArrayList<String>();
        try {
            FileReader reader = new FileReader(textName);
            int character = reader.read();
            String word = "";
            while (character != -1) {
               if(cont==n)break;
               while ((character >= 65 && character <= 90) || (character >= 97 && character <= 122)) {
                   word += (char)character;
                   character = reader.read();
               }
                if(word.length()!=0){
                    words.add(word.toLowerCase());
                    cont++;
                    word = "";
               }
                character = reader.read();
            }
            System.out.println("cant. de palabras: "+cont);
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return words;
    }

    public List<Integer> search(String word) throws Exception {
        return table.get(word);
    }
 


}
